//
//  WMMainTabbar.swift
//  swift微博项目
//
//  Created by 王明 on 15/11/8.
//  Copyright © 2015年 王明. All rights reserved.
//

import UIKit

class WMMainTabbar: UITabBar {

  //默认构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    //如果重写 init(frame:) 系统会默认为这个控件是通过代码创建
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
        //只有默认报错的语句
        //如果有调用者通过 sb / xib创建了该对象 这个时候程序就崩溃
        
        super.init(coder: aDecoder)
        setupUI()
    }
    
    
    //添加撰写的按钮
    func setupUI(){
        //添加
        addSubview(composeBtn)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //手动修改所有的按钮的位置
        //遍历所有的按钮
        let w = self.bounds.width / 5
        let h = self.bounds.height
        let rect = CGRect(x: 0, y: 0, width: w, height: h)
        
        //定义递增变量
        var index : CGFloat = 0
        for subview in subviews{
        
            if subview.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
            //修改subview的位置
                subview.frame = CGRectOffset(rect , index * w , 0)
                
                //三目运算符来确定放到那个位置
                index += index == 1 ? 2 : 1
            
            }
        }
        //撰写按钮的位置
        composeBtn.frame = CGRectOffset(rect, w * 2, 0)
        bringSubviewToFront(composeBtn)
    }

    
    
    
    
    //MARK懒加载 撰写按钮
     lazy var composeBtn:UIButton = {
    
    let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState:UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState:UIControlState.Highlighted)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.sizeToFit()
        
        return btn
    }()
    
    
}
